import React, { useEffect, useRef, useState } from 'react'

import { Button } from 'antd';
import { useTranslation } from 'react-i18next'

import chat from '../assets/images/chat-model.svg'
import chatActived from '../assets/images/chat-model-active.svg'
import {
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons';
import './styleVideo.css'
interface Bullet {
  id: number,
  text: string,
  top: number,
  progress: number
}
function VideoCom() {
  const { t } = useTranslation()
  const [isWhite, setIsWhite] = useState(false); //控制视频背景图
  const [inputText, setInputText] = useState("") // 存储输入的弹幕内容
  const [bullets, setBullets] = useState<Bullet[]>([]) // 存储弹幕数据
  const videoContainerRef = useRef<HTMLDivElement>(null) // 获取视频容器
  const bulletId = useRef(0)
  //控制箭头
  const [flag, setFlag] = useState(false)
  const [currentVideoIndex, setCurrentVideoIndex] = useState(0) // 当前视频索引

  //存储视频数据
  const [videoData, setVideoData] = useState([
    {
      id: 1,
      url: '/video/1.mp4'
    },
    {
      id: 2,
      url: '/video/2.mp4'
    },
    {
      id: 3,
      url: '/video/3.mp4'
    },
    {
      id: 4,
      url: '/video/4.mp4'
    }
  ])



  // 监听 localStorage 变化（包括当前页面和跨标签页）
  useEffect(() => {
    // 1. 定义更新状态的函数
    const updateTheme = () => {
      setIsWhite(localStorage.getItem('theme') === 'white');
    };

    // 2. 初始化主题状态
    updateTheme();

    // 3. 监听当前页面的自定义事件（手动触发）
    const handleLocalChange = () => updateTheme();
    window.addEventListener('local-storage-change', handleLocalChange);

    // 4. 监听其他标签页的 storage 事件
    window.addEventListener('storage', updateTheme);

    // 清理事件监听
    return () => {
      window.removeEventListener('storage', updateTheme);
      window.removeEventListener('local-storage-change', handleLocalChange);
    };
  }, []);

  //弹幕动画逻辑
  useEffect(() => {
    const interval = setInterval(() => {
      setBullets(prev =>
        prev.map(bullet => ({
          ...bullet,
          progress: Math.min(bullet.progress + 0.5, 100)
        })).filter(bullet => bullet.progress < 100)
      )
    }, 16)
    return () => clearInterval(interval)
  }, [])

  // 发送弹幕 
  const sendBullet = () => {
    // 1. 生成弹幕数据
    if (!inputText.trim() || !videoContainerRef.current) return

    const containerHeight = videoContainerRef.current.clientHeight
    const newBullet = {
      id: bulletId.current++,
      text: inputText,
      top: Math.random() * (containerHeight * 0.3),
      progress: 0
    }

    setBullets(prev => [...prev, newBullet])
    setInputText("")
  }

  // 切换到上一个视频
  const goToPrevVideo = () => {
    setCurrentVideoIndex(prev => (prev === 0 ? videoData.length - 1 : prev - 1));
  }

  // 切换到下一个视频
  const goToNextVideo = () => {
    setCurrentVideoIndex(prev => (prev === videoData.length - 1 ? 0 : prev + 1));
  }


  return (
    <div className={isWhite ? 'blue-video' : 'white-video'}
      style={{
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
        height: '100%',
        position: 'relative'
      }}
    >
      {/* 视频容器 */}
      <div
        ref={videoContainerRef}
        style={{
          overflow: 'hidden',
          width: '95%',
          height: 'calc(100% - 100px)', // 为底部输入区域留出空间
          position: 'relative',
          marginLeft:'20px'
        }}>
        {/* 视频列表 */}
        <div style={{
          display: 'flex',
          width: `${videoData.length * 100}%`,
          transform: `translateX(-${currentVideoIndex * (100 / videoData.length)}%)`,
          transition: 'transform 0.5s ease',
          height: '100%'
        }}>
          {videoData.map((item) => (
            <div key={item.id} style={{
              width: `${100 / videoData.length}%`,
              height: '88%',
              position: 'relative'
            }}>
              <video
                src={item.url}
                controls
                className='video'

              />
            </div>
          ))}
        </div>

        {/* 箭头按钮 */}
        <span className='left' style={{color:'#fff'}}  onClick={goToPrevVideo}><LeftOutlined /></span>
        <span className='right' style={{color:'#fff'}}   onClick={goToNextVideo}><RightOutlined /></span>
      </div>

      {/* 弹幕容器 */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom:'50%',
         height: 'calc(100% - 100px)', // 匹配视频容器高度
        zIndex: 10,
        pointerEvents: 'none',
        overflow: 'hidden',
      }}>
        {bullets.map(bullet => (
          <div key={bullet.id}
           className='bulletText'
            style={{
              position: 'absolute',
              color: isWhite ? '#000' : '#fff',
              left: `${100 - bullet.progress}%`,
              top: `${bullet.top}px`,
             
            }}
          >
            {bullet.text}
          </div>
        ))}
      </div>

      {/* 输入框和发送按钮 */}
      <div className='emitText' style={{
        position: 'absolute',
        bottom: '12%',
        width: '100%',
        height: '100px', // 固定高度
        display: 'flex',
        alignItems: 'center',
        padding: '0 50px',
        zIndex: 5, // 高于弹幕容器
      }}>
        <span
          style={{ cursor: 'pointer',marginTop:'25px' }}
          className='bullet'
          onClick={() => setFlag(!flag)}
        >
          {flag ? <img src={chatActived} alt="" /> : <img src={chat} alt="" />}
        </span>

        {flag ? (
          <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
            <input
              type="text"
              placeholder={t('bullet')}
              value={inputText}
              onChange={e => setInputText(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && sendBullet()}
              style={{
                flex: 1,
                margin: '0 10px'
              }}
            />
            <Button type='primary' className='btn' onClick={sendBullet}>{t('release')}</Button>
          </div>
        ) : (
          <p style={{ fontSize: '20px', marginLeft: '20px' }}>{t('open')}</p>
        )}
      </div>
    </div>
  )
}



export default VideoCom
